<?php

namespace App\Http\Controllers\Mobile\Personal\Auth;
use App\Facades\Site;
use App\Jobs\PersonalRegisterEmail;
use App\Models\Personal\PersonalLoginRecord;
use App\Models\Personal\PersonalUser;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth,Validator,Captcha,CustomPassword;

class AuthCommonController extends Controller{
    use AuthenticatesAndRegistersUsers, ThrottlesLogins;
    //登录以后跳转到什么位置
    protected $redirectTo = '/mobile/personal/welcome';
    //退出以后跳转到什么位置
    protected $redirectAfterLogout = '/mobile';
    protected $guard = 'personal';
    protected $loginView = 'default.mobile.personal.auth.login';
    protected $registerView = 'default.mobile.personal.auth.register';
    protected $username  = 'username';

    /**
     * 除了退出其它多要自动验证
     * AuthCommonController constructor.
     */
    public function __construct(){
        $this->middleware('guest:personal', ['except' => 'logout']);
    }

    /**
     * 个人会员前台注册验证方法
     * @param array $data
     * @return mixed
     */
    protected function validator(array $data){
        //判断是不是手机注册
        if(empty($data['mobile'])){
            $message = [
                'username.required' => '用户名称必须填写',
                'username.alpha_dash' => '用户名可以允许字母、数字、底线_',
                'username.max' => '用户名称最多20个字符',
                'username.unique' => '该用户名称已存在',
                'username.mobile' => '用户名不能使用手机号码',
                'email.required' => '邮箱必须填写',
                'email.email' => '邮箱非法,必须输入正确的邮箱格式，如12456@qq.com',
                'password.required' => '密码必须填写',
                'password.between' => '密码必须在6-20位之间',
                'password.confirmed' => '确认密码和密码必须一致',
                'code.required' =>'验证码不能为空',
                'code.captcha' => '验证码错误，请重新输入'
            ];
            return Validator::make($data, [
                'username' => 'required|max:20|alpha_dash|unique:personal_users,username|mobile',
                'email' => 'required|email',
                'password' => 'required|between:6,20|confirmed',
                'code' => 'required|captcha',
            ],$message);
        }else{
            $message = [
                'mobile.required' => '手机号码必须填写',
                'mobile.unique' => '该用户名称已存在',
                'mobile.mobile' => '请填写正确的手机号码',
                'mobCode.required' =>'验证码不能为空！',
                'mobCode.mobile_verification_code' => '手机号码和发送的验证码不匹配',
                'password.required' => '密码必须填写',
                'password.between' => '密码必须在6-20位之间',
                'password.confirmed' => '确认密码和密码必须一致'
            ];
            return Validator::make($data, [
                'mobile' => 'required|unique:personal_users,mobile|mobile_verification',
                'mobCode' => 'required|mobile_verification_code:'.$data['mobile'],
                'password' => 'required|between:6,20|confirmed'
            ],$message);
        }
    }

    /**
     * 前台注册验证字段
     * @param array $data
     * @return static
     */
    protected function create(array $data){
        if(empty($data['mobile'])){
            if(!empty($data['openid'])) {
                if (empty($data['unionid'])) {
                    $data['unionid'] = NULL;
                }
                if($data['category'] == 'qq'){
                    return PersonalUser::create([
                        'username' => $data['username'],
                        'email' => $data['email'],
                        'password' => CustomPassword::make($data['password']),
                        'qqopenid' => session('openid'),
                        'qqunionid' =>session('unionId')?session('unionId'):null,
                        'regtime' => date('Y-m-d H:i:s',time()),
                        'updatetime' => date('Y-m-d H:i:s',time()),
                        'last_login_time' => date('Y-m-d H:i:s',time()),
                        'regip' => getIp(),
                        'last_login_ip' => getIp()
                    ]);
                }else{
                    //微信
                    return PersonalUser::create([
                        'username' => $data['username'],
                        'email' => $data['email'],
                        'password' => CustomPassword::make($data['password']),
                        'wechatmpopenid' => session('openid'),
                        'wechatunionid' => session('unionid')?session('unionid'):null,
                        'regtime' => date('Y-m-d H:i:s',time()),
                        'updatetime' => date('Y-m-d H:i:s',time()),
                        'last_login_time' => date('Y-m-d H:i:s',time()),
                        'regip' => getIp(),
                        'last_login_ip' => getIp()
                    ]);
                }
            }else{
                //手机
                return PersonalUser::create([
                    'username' => $data['username'],
                    'email' => $data['email'],
                    'password' => CustomPassword::make($data['password']),
                    'regtime' => date('Y-m-d H:i:s',time()),
                    'updatetime' => date('Y-m-d H:i:s',time()),
                    'last_login_time' => date('Y-m-d H:i:s',time()),
                    'regip' => getIp(),
                    'last_login_ip' => getIp()
                ]);
            }
        }else{
            if(!empty($data['openid'])) {
                if (empty($data['unionid'])) {
                    $data['unionid'] = NULL;
                }
                if(empty($data['category']) == 'qq'){
                    return PersonalUser::create([
                        'mobile' => $data['mobile'],
                        'password' => CustomPassword::make($data['password']),
                        'qqopenid' => session('openid'),
                        'qqunionid' =>session('unionId')?session('unionId'):null,
                        'regtime' => date('Y-m-d H:i:s',time()),
                        'updatetime' => date('Y-m-d H:i:s',time()),
                        'last_login_time' => date('Y-m-d H:i:s',time()),
                        'regip' => getIp(),
                        'last_login_ip' => getIp()
                    ]);
                }else{
                    //微信
                    return PersonalUser::create([
                        'mobile' => $data['mobile'],
                        'password' => CustomPassword::make($data['password']),
                        'wechatmpopenid' => session('openid'),
                        'wechatunionid' => session('unionid')?session('unionid'):null,
                        'regtime' => date('Y-m-d H:i:s',time()),
                        'updatetime' => date('Y-m-d H:i:s',time()),
                        'last_login_time' => date('Y-m-d H:i:s',time()),
                        'regip' => getIp(),
                        'last_login_ip' => getIp()
                    ]);
                }

            }else{
                return PersonalUser::create([
                    'mobile' => $data['mobile'],
                    'password' => CustomPassword::make($data['password']),
                    'regtime' => date('Y-m-d H:i:s',time()),
                    'updatetime' => date('Y-m-d H:i:s',time()),
                    'last_login_time' => date('Y-m-d H:i:s',time()),
                    'regip' => getIp(),
                    'last_login_ip' => getIp()
                ]);
            }
        }
    }

    /**
     * 重新设置注册提交
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Foundation\Validation\ValidationException
     */
    public function register(Request $request){
        //防企业注册配置每天注册的个数（默认20个）
        $ipCount = PersonalUser::where('regip', getIp())->where('regtime','>=',date('Y-m-d H:i:s',strtotime('-1 days')))->count();
        if($ipCount >= Site::get('personalReg')){
            //  return back()->with('err','注册失败，请联系客服');
            return response()->json(['status'=>3,'msg'=>'注册失败，请联系客服']);
        }

        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }
        //注册并登录
        Auth::guard($this->getGuard())->login($this->create($request->all()));
        //登录成功后清除session
        $request->session()->forget('unionid');
        $request->session()->forget('openid');
        $request->session()->forget('category');

        $user = auth()->guard('personal')->user();
        //登录记录表
        $record = array();
        $record['uid'] = $user->uid;
        $record['personal_login_ip'] = getIp();
        $record['personal_login_time'] = date('Y-m-d H:i:s',time());
        $record['login_type'] = 3;
        //检查个人用户登录(1为普通2为QQ3为微信)手机版无微信
        if(empty($request->openId)){
            $record['type'] = 1;
        }else{
            $record['type'] = 2;
        }
        //登录记录表
        PersonalLoginRecord::create($record);

        //判断是不是手机注册
        if(!empty($request->mobile)){
            //删除验证码的session数据
            $request->session()->forget('mobile_verification');
            $request->session()->forget('mobile_verification_code');
            return response()->json(['status'=>0,'msg'=>'手机用户注册成功','redirectPath'=>url("mobile/personal/resume_create")]);
        }elseif(!empty($request->email)){
            $userInfo = (object)null;
            $userInfo->uid = $user->uid;
            $userInfo->email = $user->email;
            $userInfo->username = $user->username;
            $userInfo->password = $request->password;
            //添加到队列中
            $this->dispatch(new PersonalRegisterEmail($userInfo));
            return response()->json(['status'=>0,'msg'=>'邮箱用户注册成功','redirectPath'=>url("mobile/personal/resume_create")]);
        }
    }

    /**
     * 个人注册提交
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
//    public function postRegister(Request $request){
//        //防企业注册配置每天注册的个数（默认20个）
//        $ipCount = PersonalUser::where('regip', getIp())->where('regtime','>=',date('Y-m-d H:i:s',strtotime('-1 days')))->count();
//        if($ipCount >= Site::get('personalReg')){
//            //  return back()->with('err','注册失败，请联系客服');
//            $this->throwValidationException(
//                $request, ['32132132']
//            );
//        }
//
//        $this->register($request);
//    }

    /**
     * 前台登录验证方法
     * @param Request $request
     */
    protected function validateLogin(Request $request){
        $message = [
            $this->loginUsername().'.required' => '用户名必须填写',
            $this->loginUsername().'.alpha_dash' => '用户仅允许字母、数字、底线_',
            $this->loginUsername().'.max' => '用户名称最多32个字符',
            'password.required' => '密码必须填写',
        ];
        $this->validate($request, [
            $this->loginUsername() => 'required|alpha_dash|max:32',
            'password' => 'required',
        ],$message);
    }
}
